<template>
	<view class="file">
		<view class="fm">
			<view class="heartTips" v-if="change_recharcard_id == 2 ">温馨提示：商品提货券兑换成功后会立即生成订单！<br> 请确认需要后兑换</view>
			<view class="top">
				<view class="list" style="width:100%;" :style="{color:type == 1 ? '#4cd964' : '#b3b3b3'}" @click="onList(1)">
          <h2 style="color: #1A1A1A" v-if="change_recharcard_id == 1" > <span style="font-weight: bolder">提货券</span>序列号绑定</h2>
          <h2 style="color: #1A1A1A" v-if="change_recharcard_id == 2">   <span style="font-weight: bolder">商品券</span>序列号绑定</h2>
          <h2 style="color: #1A1A1A" v-if="change_recharcard_id == 3">   <span style="font-weight: bolder">专区券</span>序列号绑定</h2>
					<view class="son" v-if="type == 1"></view>
				</view>
			</view>
			<view class="ms">
				<view class="inp" v-if="type == 0">
            <view class="tubiao">
               <text style="font-size: 50rpx;" class="iconfont icon-zhanghao"></text>
            </view>
            <input  v-if="change_recharcard_id == 1" placeholder="请输入提货券编号"  v-model="formData.card_no" class="ms_inp" type="text">
            <input  v-if="change_recharcard_id == 2" placeholder="请输入商品券券编号"  v-model="formData.card_no" class="ms_inp" type="text">
            <input  v-if="change_recharcard_id == 3" placeholder="请输入专区券编号"  v-model="formData.card_no" class="ms_inp" type="text">
        </view>
				<view class="inp">
            <view class="tubiao"><text style="font-size: 50rpx;" class="iconfont icon-suozi"></text> </view>
            <input v-if="change_recharcard_id == 1"  placeholder="请输入提货券序列号" v-model="formData.serial"  class="ms_inp" type="text">
            <input v-if="change_recharcard_id == 2"  placeholder="请输入商品券序列号" v-model="formData.serial"  class="ms_inp" type="text">
            <input v-if="change_recharcard_id == 3"  placeholder="请输入专区券序列号" v-model="formData.serial"  class="ms_inp" type="text">
        </view>
			</view>
			<button class="btn" @click="btnChange" :disabled="disableButton" >
				绑 定
			</button>
    </view>
			<!-- <view class="txt">扫码快速绑定</view> -->
    <home v-if="navigation"></home>
    <!-- #ifdef MP -->
    <authorize v-if="isShowAuth" @authColse="authColse" @onLoadFun="onLoadFun"></authorize>
    <!-- #endif -->
	</view>
</template>

<script>
	import {recharcardUserExchange,recharcard_userRead} from '@/api/store.js'
  import home from '@/components/home';
  import {
    mapGetters
  } from "vuex";
  import {
    toLogin
  } from '@/libs/login.js';
	export default {
    components: {
      home
    },
		data() {
			return {
        isShowAuth: false, //是否隐藏授权
				type:1,
				formData:{
					card_no:'',
					serial:'',
				},
        'recharcard_user_id':'',    // 接收扫秒二维码传递的参数 提货券Id
        'recharcard_id':'',    // 接收扫秒二维码传递的参数 提货券批次参数
        change_recharcard_id: 1,   // 接收传递的提货券类型ID，当为2表示商品券时显示温馨提示
        disableButton: true,       // 仿制重复点击 禁用判断参数
        changeways:'',             // 判断兑换完成后是否跳转  userperson表示跳转到首页，默认不跳转
			}
		},
    computed: mapGetters(['isLogin']),
    watch: {
      isLogin: {
        handler: function(newV, oldV) {
          if (newV) {
            // #ifdef H5 || APP-PLUS
            // this.getUseCoupons();
            // #endif
          }
        },
        deep: true
      }
    },
		onLoad(options){
      if (!this.isLogin) {
        // #ifdef H5 || APP-PLUS
        toLogin()
        // #endif
        // #ifdef MP
        this.isShowAuth = true;
        // #endif
      }
      this.change_recharcard_id = options.id,
      this.changeways = options.changeways;
      this.disableButton = false; //页面加载的时候允许button 点击

      //扫码携带参数处理
      // #ifdef MP
      if (options.scene) {
        let value = this.$util.getUrlParams(decodeURIComponent(options.scene));
        console.log('exchange options value111111111 === : ' + JSON.stringify(value, null, 2));
        if (value.id) {
          this.recharcard_user_id = value.id;
          this.recharcard_id = value.recharcard_id;
        }
      }
      if (!this.recharcard_user_id && options.scene) {
        return this.$util.Tips({
          title: '扫码失败，请重新操作'
        }, {
          tab: 3,
          url: 1
        });
      } else {
        //请求接口获取提货券  ，进行查询操作
        this.getCardSerial()
      }
      // #endif
		},
		onShow(){
      this.disableButton = false; //页面加载的时候允许button 点击
		},
		methods: {
			onList(n){
				this.type = n
			},
      onLoadFun(){
        this.isShowAuth = false;
      },
      // 授权关闭
      authColse: function(e) {
        this.isShowAuth = e;
      },
      getCardSerial(){
        //获取详情
        recharcard_userRead(this.recharcard_user_id).then(res=>{
          console.log('res.data.info === ',res.data) // card_serial
          this.formData.serial = res.data.info.card_serial;
        })
      },
      /*
        提货券兑换方法
       */
			btnChange(){
        if (this.disableButton) return
        this.disableButton = true;
        uni.showLoading({
          title: '兑换中'
        });
        //替换字符串中的所有特殊字符（包含空格）
        const pattern=/[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g;
        if(this.formData.serial == '')
        {
          uni.showToast({
            title:'请输入序列号',
            duration:3000,
            icon:'none'
          })
          this.disableButton = false;
          return true;
        }
        this.formData.card_no = (this.formData.card_no).replace(pattern,'')
        this.formData.serial = (this.formData.serial).replace(pattern,"");

				recharcardUserExchange(this.formData).then(res=>{
          uni.hideLoading();   // 关闭提示框
          if (res.data.type == 2){  // 商品券显示加载中
            uni.showLoading({
              title: res.msg
            });
          } else {    // 通用提货券和 分类券不显示加载，显示提示语
            uni.showToast({
              title:res.msg,
              duration:3000,
              icon:'none'
            })
          }

          setTimeout(() => {
            if (this.changeways === 'userperson') {        // 跳转逻辑 userperson表示跳转到首页，默认不跳转
              this.disableButton = false;
              if (parseInt(res.data.type) === 3) {            // 分类提货券   兑换指定分类下的商品
                uni.reLaunch({
                  url: '/pages/goods/goods_list/index?sid=' + this.list.recharcard.category_id
                });
              } else if (parseInt(res.data.type) === 2) {     // 商品提货券 兑换指定商品
                let arr = []
                arr.push(res.data.card)
                uni.showLoading({
                  title: res.msg
                });
                uni.reLaunch({
                  url:'/pages/goods/order_confirm/index?cartId=' + res.data.cartId + '&recharcardId=' + res.data.card.id +'&recharcard_title='+ res.data.card.recharcard_title + '&recharcard=' + JSON.stringify(arr)
                });
              } else {                              // 通用提货券 兑换为余额
                uni.switchTab({
                  url: '/pages/index/index'
                });
              }
            }
            else {
              //不跳转逻辑   按钮恢复可点击
              this.disableButton = false;
              if (res.data.type === 2) {
                let arr = []
                arr.push(res.data.card)
                uni.showLoading({
                  title: res.msg
                });
                uni.reLaunch({
                    url:'/pages/goods/order_confirm/index?cartId=' + res.data.cartId + '&recharcardId=' + res.data.card.id +'&recharcard_title='+ res.data.card.recharcard_title + '&recharcard=' + JSON.stringify(arr)
                });
              }
            }
          }, 3000);

				}).catch(res => {
          uni.hideLoading();   // 关闭提示框
          setTimeout(()=>{
            this.disableButton = false;
          },3000)
          this.$util.Tips({
            title: res
          })
        });
			}

		}
	}
</script>

<style lang="scss">
  .heartTips{
    color: red;
    text-align: center;
    padding: 40rpx 0;
  }
	.fm{
		width: 90%;
		margin: 80rpx auto;
		background-color: #fff;
		border-radius: 20rpx;
		padding-bottom: 20rpx;
		.top{
			display: flex;
			height: 120rpx;
			line-height: 120rpx;
			justify-content: space-between;
			// border-bottom: 1px solid #ccc;
			.box{
				width: 4rpx;
				height: 40rpx;
				background-color: #b4b4b4;
				margin-top: 40rpx;
			}
			.list {
				width: 50%;
				text-align: center;
				color: rgb(6,189,4);
				position: relative;
				.son{
					width: 40rpx;
					height: 4rpx;
					background-color: rgb(6,189,4);
					position: absolute;
					bottom: 20rpx;
					left: 50%;
					margin-left: -20rpx;
				}
				// border-right: 1px solid #ccc;
			}
		}
		.ms{
			// border: 1px solid #ccc;
			// margin-top: 10rpx;

			width: 540rpx;
			margin: 0 auto 20rpx;
			box-sizing: border-box;
			.inp{
				width: 100%;
				height: 100rpx;
				border-bottom: 1rpx solid #e2e2e2;
				display: flex;
				.tubiao{
					width: 100rpx;
					height: 100%;
					text-align: center;
					line-height: 124rpx;
				}
				.ms_inp{
					width: 500rpx;
					height: 50%;
					font-size: 28rpx;
					margin-top: 36rpx;
					// border: 1px solid #ccc;
				}
			}
		}
		.btn{
			width: 540rpx;
			height: 80rpx;
			background-color: rgb(6,189,4);
			margin: 80rpx auto 10rpx;
			text-align: center;
			line-height: 80rpx;
			color: #fff;
			font-size: 36rpx;
		}
		.txt{
			width: 100%;
			text-align: center;
			color: rgb(6,189,4);
		}
	}
</style>
